<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/22
 * Time: 9:03
 */

namespace App\Http\Controllers;

use App\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PassportController extends Controller
{
    public $successStatus = 200;

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author: DaXiong
     */
    public function login(){
        $request_data['code'] = request('code','');
        $request_data['nickname'] = request('nickname','');
        $request_data['avatar'] = request('avatar','');
        $request_data['sex'] = (int)request('sex','');
      // dd($request_data);
        $app = app('wechat.mini_program');
        $data = $app->auth->session($request_data['code']);
        //dd($data);
        $userModel = new User();
        $user = $userModel->where(['openid' => $data['openid']])->first();

        //$request_data['username']=$request_data['nickname'];
        $request_data['openid']=$data['openid'];
        $request_data['password']=bcrypt($data['openid']);
        $request_data['session_key']=$data['session_key'];

        if(empty($user)){
            $userModel->create($request_data);

        }elseif($request_data['nickname'] !== '' and $request_data['avatar'] !== '' and  $request_data['sex'] !== 0){
            $user->update($request_data);
        }
        try {
//            $client = new Client();
//            $url = request()->root() . '/oauth/token';
//            $params = array_merge(config('passport.proxy'), [
//                'username' => $data['openid'],
//                'password' => $data['openid'],
//            ]);
//            $response = $client->request('POST', $url, ['form_params' => $params]);
//            $token_info = json_decode($response->getBody()->getContents());

            if (auth()->attempt(['openid' => $data['openid'], 'password' => $data['openid']])) {
                //删除用户已存在的个人token
                DB::table('oauth_access_tokens')
                    ->where('user_id', $user['id'])
                    ->delete();
                $return['token'] = $user->createToken('活动抽奖')->accessToken;
                $return['user'] = $user->toArray();
                return $this->returnJson(0, '', $return);
            }
            return $this->returnJson(0,'');
        } catch (\Exception $exception) {
            Log::error($exception);
            return $this->returnJson(1,'令牌信息获取失败');
        }
    }
    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function logout()
    {
        if (auth()->guard('api')->check()) {
            auth()->guard('api')->user()->token()->delete();
            return $this->returnJson(0,'登出成功,页面即将跳转...');
        }
        return '';
    }

    /**
     * 刷新token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function refresh(Request $request){
        try {
            $refreshToken = $request->get('refresh_token','');
            if(empty($refreshToken)){
                return $this->returnJson(1, '参数错误');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.refresh'), [
                'refresh_token' => $refreshToken,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (RequestException $exception) {
            return $this->returnJson(1);
        }
        //
        //
    }
}